#include "reportfile.h"

ReportFile::ReportFile(QString directory)
 : QFile(directory +"\\"+ REPORT_FILENAME),m_activeReport(false)
{
  #ifdef  LOG_ACTIVATED
  __TRACE__
  #endif
  #ifdef  LEAK_ACTIVATED
  __LEAK__
  #endif
  m_openingHour = QDateTime::currentDateTime();
}

ReportFile::~ReportFile()
{
  #ifdef  LOG_ACTIVATED
  __TRACE__
  #endif
  #ifdef  LEAK_ACTIVATED
  __LEAK__
  #endif
}

QString ReportFile::header() const
{
	return QDateTime::currentDateTime().toString("[dd|MM|yyyy][hh:mm:ss] ");  
}

void ReportFile::addLine(const QString& line)
{        
	if(open(QIODevice::Append|QIODevice::Text|QIODevice::WriteOnly))     
	{        
		QTextStream out(this); 
		QString add = header()+line+"\n"; 
		out <<  add;
		if(m_activeReport)
			m_report << add;
		close(); 
	}    
}  

void ReportFile::addLines(const QStringList& lines)
{        
	if(open(QIODevice::Append|QIODevice::Text|QIODevice::WriteOnly))     
	{        
		QTextStream out(this); 
		foreach(QString line,lines)
		{
			QString add = header()+line+"\n"; 
			out <<  add;
			if(m_activeReport)
				m_report << add;
		}			
		close(); 
	}    
} 

QStringList ReportFile::getReportSession()
{
	QStringList lines = readAll();
	QStringList session;
	foreach(QString line,lines)
	{
		QDateTime date = QDateTime::fromString(line.left(QString("[dd|MM|yyyy][hh:mm:ss]").size()),"[dd|MM|yyyy][hh:mm:ss]");
		if(date >= m_openingHour)
			session << line;
	}
	return session;
}



QStringList ReportFile::readAll()
{
	
	QStringList fileLines;
	if(open(QIODevice::ReadOnly))
	{
		QTextStream stream(this);
		QString line = stream.readLine();
		while(!line.isNull())
		{
			fileLines << line;
			line = stream.readLine();
		}
		close();
	}
	return fileLines;
}